<template>
  <div class="login">
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="80px"
      label-position="top"
    >
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" type="password"></el-input>
      </el-form-item>
      <el-form-item class="el-button-login">
        <el-button type="primary" @click="onSubmit" :loading="isLoading">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { login } from '@/services/user'
export default {
  name: 'login',
  data () {
    // var checkMobile = (rule, value, callback) => {
    //   const regMobil = /^[1][3,4,5,7,8][0-9]{9}$/
    //   if (regMobil.test(value)) {
    //     // 验证通过合法手机号
    //     return callback()
    //   }
    //   callback(new Error('请输入正确形式的手机号'))
    // }
    return {
      // 存储表单数据的对象
      form: {
        phone: '18201288771',
        password: '111111'
      },
      // 用于设置表单校验规则
      rules: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          // { validator: checkMobile, message: '输入正确的手机号', trigger: 'blur' }
          { pattern: /^1\d{10}$/, message: '输入正确的手机号', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { min: 6, max: 12, message: '密码长度为6到18为', trigger: 'blur' }
        ]
      },
      // 用于保存加载状态
      isLoading: false
    }
  },
  methods: {
    async onSubmit () {
      // this.$refs.form.validator(valid => { })
      try {
        // 1.设置校验
        await this.$refs.form.validate()
        // console.log(await this.$refs.form.validate())
        this.isLoading = true

        // 2.发送请求
        // const { data } = await request({
        // method: 'POST',
        // url: '/front/user/login',
        // // urlencoded 格式 名 = 值
        // data: qs.stringify(this.form)
        // })
        const { data } = await login(this.form)

        this.isLoading = false
        // console.log(data)
        // 3.相应数据处理
        if (data.state !== 1) {
          return this.$message.error(data.message)
        }
        // 将用户信息存储到vuex 中
        this.$store.commit('setUser', data.content)
        // 根据可能存在 的 redirect 数据进行跳转设置
        this.$router.push(this.$route.query.redirect || '/')
        // console.log(this.$route)
        this.$message.success(data.message)
      } catch (err) {
        // this.$message.error('未通过校验')
        console.log('未通过校验')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.login {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  .el-form {
    background-color: #fff;
    padding: 20px;
    width: 300px;
    border-radius: 10px;
    .el-button-login {
      text-align: right;
    }
  }
}
</style>
